package com.shop.cereshop.app.dl.logic.controller;

import com.alibaba.fastjson.JSONObject;
import com.shop.cereshop.app.dl.logic.domian.RequestHead;
import com.shop.cereshop.app.dl.logic.domian.Result;
import com.shop.cereshop.app.dl.logic.service.Impl.SendPostImpl;
import com.shop.cereshop.app.dl.logic.utils.JsonUtils;
import com.shop.cereshop.app.dl.logic.utils.ResultInfo;
import com.shop.cereshop.app.dl.logic.utils.WeixinUtil;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @Author YF
 * @Date 日期:2021/6/25 时间:17:34
 */
@RestController
@CrossOrigin
@RequestMapping("/Tongcheng")
public class DlRequestZxkController {
    @Value("${weixin.expire_seconds}")
    private Integer expire_seconds;

    @Autowired
    private RestTemplate restTemplate;
    @Value("${Dl_Data.version}")
    private String version;
    @Value("${Dl_Data.userId}")
    private String user_id;
    @Value("${Dl_Data.name}")
    private String user_key;

    @Autowired
    private SendPostImpl sendPost;

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.expires_in}")
    private Long expires_in;

    @Value("${weixin.secret}")
    private String secret;

    @Autowired
    private StringRedisService stringRedisService;

    /**
     *
     * @description:订单核销接口（自己提供）
     * @param
     * @return:
     *
     * @author:作者:YF
     * @time:日期:2021/6/25  时间:14:05
     */
    @PostMapping(value = "/ProcessRequest",produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result getConsumeNotice(@RequestBody String request){
        System.out.println(request);
        return sendPost.ConsumeNotice(request);
    }

    // 生成带参数的二维码，扫描关注微信公众号
    @RequestMapping(value = "/wechat/mpLogin")
    public ResultInfo<?> wechatMpLogin() throws Exception {
        //获取缓存中的token
        String accessToken = (String) stringRedisService.get(appId + secret + "accessToken");
        Map map = null;
        //没有在查询
        if("".equals(accessToken) || accessToken == null){
            try {
                accessToken = WeixinUtil.getAccessToken(appId, secret);
                stringRedisService.set(appId + secret + "accessToken",accessToken, expires_in*1000);
//                accessToken = (String) map.get("access_token");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String scene_str = "lrfun.com." + System.currentTimeMillis();
        String params = "{\"expire_seconds\":" + expire_seconds + ", \"action_name\":\"QR_STR_SCENE\", \"action_info\":{\"scene\":{\"scene_str\":\"" + scene_str + "\"}}}";
        Map<String, Object> resultMap = WechatUtil.httpClientPost(url, params);

        //把缓存中的token保存下来,对比
        String temp = accessToken;
        //判断是否有错误码,有则说明没有调到,则重新调用一次
        if(!WeixinUtil.isTokenFlag(resultMap)){
            accessToken = WeixinUtil.getAccessToken(appId, secret);
            //如果相等,说明没有更新,直接调用微信的接口
            if(temp.equals(accessToken)){
                accessToken = WeixinUtil.getAccessTokenTwo(appId, secret);
            }
//            accessToken = (String) map.get("access_token");
            stringRedisService.set(appId + secret + "accessToken", accessToken, expires_in*1000);
            //重新调用方法, 更新数据
            resultMap = WechatUtil.httpClientPost(url, params);
        }

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        if (resultMap.get("ticket") != null) {
            String qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + resultMap.get("ticket");
            stringObjectHashMap.put("qrcodeUrl", qrcodeUrl);
        }
        stringObjectHashMap.put("scene_str", scene_str);
        return new ResultInfo<>(stringObjectHashMap);
    }

    // 回调函数
    public void callback(HttpServletRequest httpServletRequest) throws Exception {
        Map<String, String> callbackMap = WechatUtil.xmlToMap(httpServletRequest); //获取回调信息
        //下面是返回的xml
        //<xml><ToUserName><![CDATA[gh_f6b4da984c87]]></ToUserName> //微信公众号的微信号
        //<FromUserName><![CDATA[oJxRO1Y2NgWJ9gMDyE3LwAYUNdAs]]></FromUserName> //openid用于获取用户信息，做登录使用
        //<CreateTime>1531130986</CreateTime> //回调时间
        //<MsgType><![CDATA[event]]></MsgType>
        //<Event><![CDATA[SCAN]]></Event>
        //<EventKey><![CDATA[lrfun.com.UxJkWC1531967386903]]></EventKey> //上面自定义的参数（scene_str）
        //<Ticket><![CDATA[gQF57zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyY2ljbjB3RGtkZWwxbExLY3hyMVMAAgTvM0NbAwSAOgkA]]></Ticket> //换取二维码的ticket
        //</xml>
        if (callbackMap != null) {
            callbackMap.get("FromUserName");
            // 通过openid获取用户信息
            // 将数据写入到数据库中，前面自定义的参数（scene_str）也需记录到数据库中，后面用于检测匹配登录
            // INSERT INTO wechat_user_info......(数据库操作)
        }
    }


    public String destroyTicket(){
        //.返回参数
        String result = "";
        //.定义时间
        long st = System.currentTimeMillis() / 1000;
        //封装请求参数
        String string = "" + "{" +
                "orderSerialId:\"" + "564415944899814" + "\"," +
                "partnerOrderId:\"" + "1000071955" + "\"," +
                "tickets:" + 1 + "," +
                "consumeDate:\"" + "2018-07-04 12:09:40" + "\"," +
                "totalCheckCount:" + 1 +
                "}";
        //加密将json格式的业务参数进行des加密，加密模式ECB充方式 PKCS7Padding,密钥为user_key。
        String encrypt = null;
        try {
            encrypt = SendPostImpl.encrypt(string, user_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String md5 = SendPostImpl.getMD5(user_id + "ConsumeNotice" + st + version + encrypt + user_key);
        //.封装JSON格式数据
        JSONObject json = new JSONObject();
        RequestHead requestHead = new RequestHead();
        requestHead.setUser_id(user_id);
        requestHead.setMethod("ConsumeNotice");
        requestHead.setTimestamp(st);
        requestHead.setVersion(version);
        requestHead.setSign(md5);
        json.put("requestHead", requestHead);
        json.put("requestBody", encrypt);
        //.请求地址URL
        String url = "http://192.168.2.20:6312/Tongcheng/ProcessRequest";
        System.out.println("请求参数json是："+json);
        //.发送请求
        String resultInfo = restTemplate.postForObject(url,json,String.class);
        try {
            result = SendPostImpl.decrypt((String) JsonUtils.toMap(resultInfo).get("responseBody"), user_key);
            System.out.println("响应结果"+result);
        } catch (Exception e) {
            System.out.println("请求失败");
            return resultInfo;
        }
        return result;
    }



}
